package org.example.leecode;

import java.util.Stack;

public class Leecode20 {
    public boolean isValid(String s) {
        if(s.length() % 2 != 0){
            return false; // 如果字符串长度为奇数，绝对不匹配
        }
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if(c == '(' && c == '[' && c == '{'){
                stack.push(c); //如果是左括号，便入栈
            }
            else {
                if(stack.isEmpty()){
                    return false; //栈顶元素不存在
                }
                char top = stack.pop();
                if( c == ')' && top != '(') return false;
                if( c == ']' && top != '[') return false;
                if( c == '}' && top != '{') return false;
            }
        }
        return stack.isEmpty(); //栈为空才算匹配
    }
}
